#coding:utf-8
#-*- coding: UTF-8 -*-

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

import os
import signal
import subprocess

from com.android.monkeyrunner import MonkeyRunner as mr
from com.android.monkeyrunner import MonkeyDevice as md
from com.android.monkeyrunner import MonkeyImage  as mi

import time
#设备清单
deviceDict={
    'HW017':'CYSBBBA751208908',
    'HW003':'CYSBBBA751212401',
    'HW007':'CYSBBBA751214840',
    'HW014':'CYSBBBA751800606',
    'HW005':'CYSBBBA751802051',
    'HW008':'CYSBBBA751808117',
    'HW009':'CYSBBBE742630290',
    'HW018':'CYSBBBE752004178',
    'HW004':'CYSBBBE752024803',
    'HW006':'CYSBBBE752314628'
}

deviceName=sys.argv[1]
if deviceName not in deviceDict:
    print('没有指定设备')
    sys.exit(1)


device = None
image = None
directory=r'E:\mobileCharge'   #脚本所在目录配置
deviceSerialNo=deviceDict[deviceName]
print(directory,deviceName,deviceSerialNo)

#屏幕竖屏时的宽高
screenWidth=720
screenHeight=1280

serverCountPerGroup=100#每区服组区服数量
serverCountPerPage=9 #每页区服数

#脚本文件配置
taskPyFile      ='%s\\getTask.py'%directory    #获取任务
rotatePyFile    ='%s\\image_rotate.py'%directory   #旋转图片
ocrServerPyFile ='%s\\ocrServer.py'%directory  #识别区服
saveResultPyFile='%s\\saveResult.py'%directory  #保存结果

#界面判断顺序
page_sort=['active','combine', 'info','gameInit','gameInit2','selectServer','beforeServer','beforeServer2','role']
#界面
pages={
    'active':[#活动，白色底
        {'x': 266, 'y': 106, 'r': 255, 'g': 255, 'b': 255},
        {'x': 930, 'y': 108, 'r': 255, 'g': 255, 'b': 255},
        {'x': 512, 'y': 585, 'r': 247, 'g': 247, 'b': 247}
    ],
    'info':[#完善个人资料  白色底
        {'x': 335, 'y': 90, 'r': 249, 'g': 249, 'b': 249},
        {'x': 830, 'y': 90, 'r': 249, 'g': 249, 'b': 249},
        {'x': 358, 'y': 626, 'r': 245, 'g': 245, 'b': 245} #取消 按钮
    ],
    'combine' : [#全区公告，合服，维护   游戏内置的
        {'x': 277, 'y': 157, 'r': 17, 'g': 17, 'b': 17},
        {'x': 900, 'y': 157, 'r': 18, 'g': 15, 'b': 14},
        {'x': 552, 'y': 540, 'r': 152, 'g': 36, 'b': 21}
    ],
    'gameInit':[#游戏初始,等待点击进入
        {'x': 1155, 'y': 650, 'r': 42, 'g': 33, 'b': 24},
        {'x': 100, 'y': 100, 'r': 114, 'g': 98, 'b': 66},
        {'x': 550, 'y': 661, 'r': 49, 'g': 41, 'b': 28}
    ],
    'gameInit2': [  # 游戏初始,等待点击进入
        {'x': 1155, 'y': 650, 'r': 42, 'g': 33, 'b': 24},
        {'x': 100, 'y': 100, 'r': 114, 'g': 98, 'b': 66},
        {'x': 550, 'y': 661, 'r': 255, 'g': 0, 'b': 0}
    ],

    'beforeServer': [  # 选区前一步操作，       可能性1
        {'x': 1155, 'y': 650, 'r': 42, 'g': 33, 'b': 24},
        {'x': 100, 'y': 100, 'r': 114, 'g': 98, 'b': 66},
        {'x': 550, 'y': 661, 'r': 159, 'g': 75, 'b': 28}#进入游戏 按钮
    ],
    'beforeServer2': [  # 选区前一步操作，      可能性2
        {'x': 1155, 'y': 650, 'r': 255, 'g': 0, 'b': 0},
        {'x': 100, 'y': 100, 'r': 114, 'g': 98, 'b': 66},
        {'x': 550, 'y': 661, 'r': 159, 'g': 75, 'b': 28}  # 进入游戏 按钮
    ],
    'selectServer':[#选区界面
        {'x': 194, 'y': 172, 'r': 21, 'g': 18, 'b': 17},
        {'x': 1037, 'y': 530, 'r': 61, 'g': 46, 'b': 30}
    ],
    'role':[#角色界面
        {'x': 169, 'y': 651, 'r': 151, 'g': 64, 'b': 26},#返回 按钮
        {'x': 681, 'y': 50, 'r': 27, 'g': 30, 'b': 36},#
        {'x': 1118, 'y': 651, 'r': 150, 'g': 63, 'b': 26},#进入游戏 按钮
    ]
}

def exitGracefully(signum, frame):
    signal.signal(signal.SIGINT, signal.getsignal(signal.SIGINT))
    device.shell('killall com.android.commands.monkey')
    sys.exit(1)


#获取分组,左侧分组选择
def getGroupByServer(server):#获取区服分组
    maxServer=getPageMaxServer()
    min = (maxServer - 1) / serverCountPerGroup * serverCountPerGroup
    max = min + serverCountPerGroup
    print(min, max, '------', server)
    if min < server and server <= max:
        print('fast finded')
        return True

    findPage = False
    findTimes = 10
    while not findPage and findTimes > 0:
        image = device.takeSnapshot()
        #subImage = getSubImage(image, 221, 188, 340, 466)
        subImage = getSubImage(image, 221, 188, 340, 466)
        serverImagePath = r"%s\image\server\server_%s_%d.jpg" % (directory, deviceName, taskId)
        subImage.writeToFile(serverImagePath, 'jpg')
        child = subprocess.Popen(['python', rotatePyFile, serverImagePath])  # 旋转图片
        child.wait()
        selectServerProcess = subprocess.Popen(['python', ocrServerPyFile, serverImagePath,'group'], shell=True,
                                               stdout=subprocess.PIPE)
        selectServerProcess.wait()
        result = selectServerProcess.stdout.read().strip('\n').strip('\r')

        print('the group is', result)

        try:
            serverArr = result.split(',')
        except ValueError:
            print 'result is wrong'
        isBig = False
        isSmall = False
        isEqual = False
        for one in serverArr:
            try:
                min,max=one.split('-')
            except ValueError:
                continue
            min=int(min)
            max=int(max)
            if min<=server<=max:
                isEqual = True
                break
            elif server<min:
                isSmall = True
            elif server>max:
                isBig = True


        if isEqual:
            print('the group is find:', server)
            findPage = True
        else:
            findTimes -= 1
            if isSmall:
                drag((220, 465), (220, 265), 0.1)
            elif isBig:
                drag((220, 365), (220, 565), 0.1)
    if findPage:
        print('finded group ------------')
        pleft = 330;
        top = 190;
        heightDiff = 60
        touchPoint = [
            (pleft, top + heightDiff * 0),
            (pleft, top + heightDiff * 1),
            (pleft, top + heightDiff * 2),
            (pleft, top + heightDiff * 3),
            (pleft, top + heightDiff * 4)
        ]

        for point in touchPoint:
            touch(point[0], point[1])
            #sleep(1)
            maxServer = getPageMaxServer()
            min=(maxServer-1) / serverCountPerGroup * serverCountPerGroup
            max=min+serverCountPerGroup
            print(min,max,'------',server)
            if min<server and server<=max :
                return True
    else:
        print('not find the group')

# 屏幕坐标转为实际坐标
def getLocalXY(x, y):
    lx = screenWidth - y;
    ly = x
    return lx, ly

# 屏幕中可见的坐标，获取子图
def getSubImage(image, left, top, right, bottom):
    x1, y1 = getLocalXY(left, top)
    x2, y2 = getLocalXY(right, bottom)
    return image.getSubImage((x2, y1, x1 - x2, y2 - y1))

# 获取当前选中的区服
def getCurrentServer():
    if True:  # 获取当前选中的区服
        image = device.takeSnapshot()
        subImage = getSubImage(image, 512, 580, 602, 610)
        serverImagePath = r"%s\image\server\server_%s_%d.png" % (directory, deviceName, taskId)
        subImage.writeToFile(serverImagePath, 'png')
        child = subprocess.Popen(['python', rotatePyFile, serverImagePath])  # 旋转图片
        child.wait()
        selectServerProcess = subprocess.Popen(['python', ocrServerPyFile, serverImagePath,'server'], shell=True,
                                                   stdout=subprocess.PIPE)
        selectServerProcess.wait()
        result = selectServerProcess.stdout.read().strip('\n').strip('\r')
        print('current server is', result)
        try:
            intval = int(result)
        except ValueError, e:
            intval = -1
        finally:
            return intval

def getPageMaxServer():
    image = device.takeSnapshot()
    subImage = getSubImage(image, 440, 307, 550, 342)
    serverImagePath = r"%s\image\server\server_%s_%d.png" % (directory, deviceName, taskId)
    subImage.writeToFile(serverImagePath, 'png')
    child = subprocess.Popen(['python', rotatePyFile, serverImagePath])  # 旋转图片
    child.wait()

    selectServerProcess = subprocess.Popen(['python', ocrServerPyFile, serverImagePath, 'server'], shell=True,
                                               stdout=subprocess.PIPE)
    selectServerProcess.wait()
    result = selectServerProcess.stdout.read().strip('\n').strip('\r')
    try:
        intval=int(result)
    except ValueError,e:
        intval=-1
    finally:
        return intval


def checkOnePage(pointArr):
    global image
    isfix = True
    for point in pointArr:
        localX, localY = getLocalXY(point['x'], point['y'])
        color = image.getRawPixel(localX, localY)
        if color[1] != point['r'] \
                or color[2] != point['g'] \
                or color[3] != point['b']:
            print('wait point ', point)
            print(color)
            isfix = False
            break
    return isfix

# 等待指定坐标
def waitFor(pointArr, times):
    global image
    tryTime = times
    while tryTime > 0:
        tryTime -= 1
        image = device.takeSnapshot()
        if checkOnePage(pointArr):
            return True
    return False


def saveResult(taskId,server,result,deviceNum):
    usedTime = time.time() - timeBegin
    taskProcess = subprocess.Popen(['python', saveResultPyFile, str(taskId), str(server), str(usedTime), result,deviceNum], shell=True)
    taskProcess.wait()


#连接设备(等待时间，‘版本号’)
def connectDevice(deviceSerialNo):
    global device
    tryTimes=1;connect=False
    while tryTimes<=3 :
        print('connecting: %s ...%d' % (deviceName,tryTimes))
        device = mr.waitForConnection(5,deviceSerialNo)
        try:
            device.wake()
        except :
            tryTimes+=1
            continue
        else:
            print("the device is connected")
            connect=True
            break
    if not connect:
        mr.alert(u'设备：%s没有连接上，请确认连接线是否插牢，或手机未授权'%deviceName)
    return connect


#沉睡后唤醒
def sleep(seconds):
    time.sleep(seconds)




def touch(x,y):
    global device
    res = device.wake()
    print("------------wake:", res)

    if not res:
        connect=connectDevice(deviceSerialNo)
        if connect:
            device.touch(x,y,md.TouchPressType.DOWN_AND_UP)
        else:
            return False
    else:
        device.touch(x, y, md.TouchPressType.DOWN_AND_UP)
        return True


def drag(p1,p2,second):
    global device
    try:
        device.wake()
    except:
        connect = connectDevice(deviceSerialNo)
        if connect:
            device.drag(p1, p2, second)
        else:
            return False
    else:
        device.drag(p1, p2, second)
        return True

#判断当前是哪个页面
def checkPage():
    global pages,device,image
    image = device.takeSnapshot()
    for page in page_sort:
        if checkOnePage(pages[page]):
            return page
    else:
        return None





#选区服
def selectServer():
    #定位分组
    getGroupByServer(server)

    if True:#获取最大开区,便于快速定位到中间位置，    本逻辑可以省略
        maxServer=getPageMaxServer()
        remander=maxServer % serverCountPerGroup
        baseServer=(maxServer-1)/serverCountPerGroup*serverCountPerGroup+1
        if remander==0:
            remander=serverCountPerGroup
        middleServer=remander/2+baseServer
        #drag((645, 465), (645, 40), 0.1)#
        if(server>middleServer):#正向
            pass
        else:#拉到中间
            i=1
            while i<3:
                i+=1
                drag((645, 500), (645, -500), 0.1)
            print('position fix is over--------')

    if True:#寻找区服
        print('-----------------begin find--------------')
        findPage=False
        findTimes=30
        while not findPage and findTimes>0:
            #选择区服截图
            image = device.takeSnapshot()
            subImage = getSubImage(image, 436,299, 1100, 512)
            serverImagePath=r'%s\image\server\server_%s_%d.jpg'%(directory,deviceName,taskId)
            subImage.writeToFile(serverImagePath,'jpg')
            child=subprocess.Popen(['python', rotatePyFile, serverImagePath]) #旋转图片
            child.wait()

            selectServerProcess=subprocess.Popen(['python',ocrServerPyFile,serverImagePath,'server'],stdout=subprocess.PIPE)
            selectServerProcess.wait()
            result=selectServerProcess.stdout.read().strip('\n').strip('\r')
            serverArr=result.split(',')
            isBig=False
            isSmall=False
            isEqual=False
            for one in serverArr:
                print one
                try:
                    se=int(one)
                except ValueError,e:
                    continue

                if se>server:
                    isBig=True
                elif se<server:
                    isSmall=True
                elif se==server:
                    isEqual=True
                    break

            if isEqual:
                print('the server is find:',server)
                findPage=True
            else:
                findTimes-=1
                if isSmall:
                    drag((645, 365), (645, 680), 0.2)
                elif isBig:
                    drag((645, 465), (645, 80), 0.2)


        if findPage:#找到后，选中区服
            print('find ',server)
            # 点击坐标
            pleft = 470;        pcenter = 700;        pright = 914
            top = 320;        middle = 400;        bottom = 480
            heightDiff=50
            touchPoint=[
                (pleft,top),(pcenter,top),(pright,top),
                (pleft,middle),(pcenter,middle),(pright,middle),
                (pleft,bottom),(pcenter,bottom),(pright,bottom),
                (pleft, top+heightDiff), (pcenter, top+heightDiff), (pright, top+heightDiff),
                (pleft, middle+heightDiff), (pcenter, middle+heightDiff), (pright, middle+heightDiff),
                        ]

            for point in touchPoint:
                device.touch(point[0], point[1], md.TouchPressType.DOWN_AND_UP)
                #sleep(1)
                if getCurrentServer()==server:
                    saveResult(taskId, server, 'find',deviceName)
                    print('select the server')
                    break
            else:
                print('not select')

        else:
            saveResult(taskId, server, 'notfindserver',deviceName)
            print('not find ',server)



if __name__ == '__main__':
    signal.signal(signal.SIGINT, exitGracefully)

connect = connectDevice(deviceSerialNo)
while connect:
    timeBegin = time.time()
    taskId=1
    server=101

    if True:#提取任务
        taskProcess=subprocess.Popen(['python',taskPyFile,deviceName],shell=True,stdout=subprocess.PIPE)
        taskProcess.wait()
        result=taskProcess.stdout.read().strip('\n').strip('\r')
        taskId,server,account,password,role,area,rechargeType,money=result.split('~')

        taskId          = int(taskId)
        server          = int(server)
        account         = account.strip()
        password        = password.strip()
        role            = role.strip()
        area            = area.strip()
        rechargeType    = rechargeType.strip()
        money           = float(money)
        print(taskId,server,account,password,role,area,rechargeType,money)

    # 开启应用
    if True:
        print('open app')
        device.shell('am force-stop com.shenghe.wzcq.huawei --user 0')
        sleep(2)
        device.startActivity(component="com.shenghe.wzcq.huawei/.FirstActivity")
        sleep(2)

    flag_enter_server=False #有过选区
    while True:
        page=checkPage()
        print(page)
        if page==None:
            print('unknow page')
            continue

        point = pages[page][-1]

        if page=='active':
            touch(point['x'],point['y'])
            sleep(2)
            pass
        elif page=='info':
            touch(point['x'], point['y'])
        elif page=='combine':
            touch(point['x'], point['y'])
            sleep(2)
            pass
        elif page=='gameInit' or page=='gameInit2':
            point = pages[page][0]
            touch(point['x'], point['y'])
            sleep(2)
            pass
        elif page=='beforeServer' or page=='beforeServer2':
            touch(703,594)
            sleep(2)
            pass
        elif page=='selectServer':
            selectServer()
            flag_enter_server=True

        elif page=='role':
            if flag_enter_server:#有选过区,进入游戏
                touch(point['x'], point['y'])
            else:#未选过区，返回
                point = pages[page][0]
                touch(point['x'], point['y'])





